package vg.modules.util_plugins;


import vg.services.graph_view_manager.interfaces.graph_view.AGraphView;
import vg.services.graph_view_manager.interfaces.tab.ATab;
import vg.services.graph_view_manager.realization.graph_view.smart_graph_view.realization.actions.UndoRedoAction;
import vg.services.main_manager.VGMainServiceHelper;
import vg.services.plugin_manager.event_and_request.event.AUIEvent;
import vg.services.plugin_manager.event_and_request.event.UIEventChangeTab;
import vg.services.plugin_manager.interfaces.IPlugin;
import vg.services.user_interface_manager.interfaces.UserInterfaceObserverAdapter;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class UndoRedoButtonPlugin implements IPlugin{
	private AGraphView view;

	@Override
    public void install() throws Exception {
		final JMenuItem redoMenuItem = new JMenuItem("Redo");
        redoMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_DOWN_MASK));
        redoMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(view != null) {
					view.addAction(new UndoRedoAction(UndoRedoAction.REDO_ACTION));
				}
			}
		});

        final JMenuItem undoMenuItem = new JMenuItem("Undo");
        undoMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK));
        undoMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(view != null) {
                    view.addAction(new UndoRedoAction(UndoRedoAction.UNDO_ACTION));
                }
			}
		});

        VGMainServiceHelper.userInterfaceManager.addObserver(new UserInterfaceObserverAdapter() {
            @Override
            public void dispatchEvent(AUIEvent event) {
                switch(event.getType()) {
                    case DEF_CHANGE_TAB: {
                        UIEventChangeTab bufEvent = (UIEventChangeTab)event;
                        ATab tab = bufEvent.getTab();
                        if (tab != null) {
                            switch (tab.getTabType()) {
                                case ATab.DEF_GRAPH_VIEW_TAB_TYPE: {
                                    view = (AGraphView)tab;
                                    break;
                                }
                            }
                        }
                        break;
                    }

                    default:
                        break;
                }
            }
        });

        VGMainServiceHelper.userInterfaceManager.addMenuItem(undoMenuItem, "edit");
        VGMainServiceHelper.userInterfaceManager.addMenuItem(redoMenuItem, "edit");
	}
}
